#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<time.h>

//递归
void _MergeSort(int* a, int left, int right, int* tmp) {
	if (left >= right)
		return;

	int mid = (left + right) / 2;
	_MergeSort(a, left, mid, tmp);
	_MergeSort(a, mid + 1, right, tmp);

	//类似合并两个有序链表
	int begin1 = left, end1 = mid, begin2 = mid + 1, end2 = right;
	int index = left;
	while (begin1 <= end1 && begin2 <= end2) {
		if (a[begin1] <= a[begin2]) {
			tmp[index++] = a[begin1++];
		}
		else {
			tmp[index++] = a[begin2++];
		}
	}

	//拷贝剩余数据
	while (begin1 <= end1) {
		tmp[index++] = a[begin1++];
	}
	while (begin2 <= end2) {
		tmp[index++] = a[begin2++];
	}

	//拷贝回原数组
	for (int i = left; i <= right; i++) {
		a[i] = tmp[i];
	}
}
void MergeSort(int* a, int n) {
	int* tmp = (int*)malloc(sizeof(int) * n);
	_MergeSort(a, 0, n - 1, tmp);
	free(tmp);
}

//非递归
void MergeSortNone(int* a, int n) {
	int* tmp = (int*)malloc(sizeof(int) * n);
	int gap = 1;
	while (gap < n) {
		for (int i = 0; i < n; i += gap * 2) {
			int begin1 = i, end1 = i + gap - 1, begin2 = i + gap, end2 = i + 2 * gap - 1;
			//左边界溢出
			if (begin2 >= n) {
				break;
			}
			//右边界溢出
			if (end2 >= n) {
				end2 = n - 1;
			}

			int index = i;
			while (begin1 <= end1 && begin2 <= end2) {
				if (a[begin1] <= a[begin2]) {
					tmp[index++] = a[begin1++];
				}
				else {
					tmp[index++] = a[begin2++];
				}
			}
			while (begin1 <= end1) {
				tmp[index++] = a[begin1++];
			}
			while (begin2 <= end2) {
				tmp[index++] = a[begin2++];
			}
			//拷贝回原数组
			for (int j = i; j <= end2; j++) {
				a[j] = tmp[j];
			}
		}
		gap *= 2;
	}
	free(tmp);
}

void print(int *a, int n) {
	for (int i = 0; i < n; i++)
		printf("%d ", a[i]);
	printf("\n");
}

void test() {
	int a[] = { 1,2,3,5,4,6,7,0,8,9 };
	MergeSortNone(a, sizeof(a) / sizeof(a[0]));
	print(a, sizeof(a) / sizeof(a[0]));
}

void TestOP()
{
	srand(time(0));
	const int N = 99999;
	int* a4 = (int*)malloc(sizeof(int) * N);

	for (int i = 0; i < N; ++i)
	{
		a4[i] = rand();
	}
	int begin4 = clock();
	MergeSortNone(a4, N);
	int end4 = clock();
	printf("MergeSortNone:%d\n", end4 - begin4);
	free(a4);
}

int main() {
	test();
	TestOP();
	return 0;
}